package com.stock.stockana.ui.adapter;

import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.andexert.library.RippleView;
import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.R;
import com.stock.stockana.StockCenter;
import com.stock.stockana.beans.SimpleStock;
import com.stock.stockana.beans.StockInfoBean;
import com.stock.stockana.model.StockCursorLoader;
import com.stock.stockana.requests.AddStock;
import com.stock.stockana.requests.DeleteStock;
import com.stock.stockana.requests.GetAllStocks;
import com.stock.stockana.requests.GetOneStock;
import com.stock.stockana.ui.activities.SelectStockActivity;
import com.stock.stockana.ui.listener.OnStockItemClickedListener;

import java.util.ArrayList;
import java.util.List;

/**
 * ---------------------------------------------------
 * Description: 添加自选股页面的适配器,内部实现自动加载数据，来进行页面的内容适配
 * Author: ljgsonx
 * Belong to: com.stock.stockana.Adapter
 * Time: 2016/1/20 17:14
 * ---------------------------------------------------
 */
public class SearchedStockAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  implements LoaderManager.LoaderCallbacks<Cursor>{

    private Context mContext;
    private static List<SimpleStock> mStocks;
    private LayoutInflater mLayoutInflater;

    private EditText mSearchEt;
    private ImageView mCancelSearchKeyIv;

    private LoaderManager mLoaderManager;

    private final static int VIEWTYPE_TITLE = 1;
    private final static int VIEWTYPE_CONTENT = 2;

    private boolean mHasCollected;
    private boolean mRequestFinished = true;

    public SearchedStockAdapter(Context mContext, LoaderManager loaderManager) {
        this.mContext = mContext;
        mLayoutInflater = LayoutInflater.from(mContext);
        this.mLoaderManager = loaderManager;
        if(null == mStocks) mStocks = new ArrayList<SimpleStock>();
    }

    public OnStockItemClickedListener mOnItemClickListener;

    public void setOnItemClickedListener(OnStockItemClickedListener listener) {
        this.mOnItemClickListener = listener;
    }

    /**
     * 创建ViewHolder
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == VIEWTYPE_TITLE){
            View mView = mLayoutInflater.inflate(R.layout.select_stock_tv, parent, false);
            mSearchEt = (EditText) mView.findViewById(R.id.searchStockEt);
            mCancelSearchKeyIv = (ImageView) mView.findViewById(R.id.cancelSearchKeyIv);
            mSearchEt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    String inputedStr = mSearchEt.getText().toString();
                    if(StringUtil.isBlank(inputedStr)) {
                        mStocks.clear();
                        notifyDataSetChanged();
                        return;
                    }
                    StockCursorLoader.mSearchKey = inputedStr;
                    mLoaderManager.initLoader(StockCursorLoader.ID, null, SearchedStockAdapter.this).forceLoad();
                }
            });
            mCancelSearchKeyIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSearchEt.setText("");
                    mStocks.clear();
                    notifyDataSetChanged();
                }
            });
            return new TitleHolder(mView);
        }else{
            View mView = mLayoutInflater.inflate(R.layout.select_stock_item, parent, false);
            return new StocksHolder(mView);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return VIEWTYPE_TITLE;
        }else {
            return VIEWTYPE_CONTENT;
        }
    }

    /**
     * 绑定ViewHoler，给item中的控件设置数据
     */
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if(position != 0){

            setItemValue((StocksHolder)holder,position-1);

            if (mOnItemClickListener != null) {
                ((StocksHolder) holder).select_stock_item_Rv.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        if (mRequestFinished) {
                            boolean notCollected = true;
                            String stockNum = mStocks.get(position - 1).getStNum();
                            for (StockInfoBean sb : GetAllStocks.stocks) {
                                if (!StringUtil.isBlank(stockNum)) {
                                    if (stockNum.equals(sb.getStNum())) {
                                        mOnItemClickListener.onStockItemCliked(sb);
                                        notCollected = false;
                                        break;
                                    }
                                }
                            }
                            if (notCollected) {
                                GetOneStock gos = GetOneStock.build().setStockNum(stockNum).setAction(GetOneStock.ACTION_OPENSTOCK);
                                StockCenter.doReq(gos);
                                ((SelectStockActivity) mContext).startPopLoadingByPacMan((View) holder.itemView.getParent(), "正在打开详情页...");
                                mRequestFinished = false;
                            }
                        }else{
                            Toast.makeText(mContext, "操作太快啦~", Toast.LENGTH_SHORT).show();
                        }

                    }
                });
            }
        }else{
            setEditTvFocused();
        }
    }

    private void setItemValue(final StocksHolder holder, final int position) {
        final String stockNum = mStocks.get(position).getStNum();
        String stockName =mStocks.get(position).getStName();
        holder.stockNumTv.setText(stockNum);
        holder.stockNameTv.setText(stockName);
        mHasCollected = false;
        for(StockInfoBean sb: GetAllStocks.stocks){
            if(!StringUtil.isBlank(stockNum)){
                if(stockNum.equals(sb.getStNum())){
                    mHasCollected = true;
                    break;
                }
            }
        }
        ColorStateList whiteColor = mContext.getResources().getColorStateList(R.color.c_light_white);
        holder.stockCollectionBtn.setTextColor(whiteColor);
        if(mHasCollected){
            holder.stockCollectionBtn.setText("取消");
            holder.stockCollectionBtn.setSelected(true);
            holder.stockCollectionBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mRequestFinished) {
                        DeleteStock deleteStock = DeleteStock.build().setStockNum(stockNum);
                        StockCenter.doReq(deleteStock);
                        ((SelectStockActivity)mContext).startPopLoadingByPacMan((View) holder.itemView.getParent(), "正在删除自选股...");
                        mRequestFinished = false;
                    } else {
                        Toast.makeText(mContext, "操作太快啦~", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }else{
            holder.stockCollectionBtn.setText("添加");
            holder.stockCollectionBtn.setSelected(false);
            holder.stockCollectionBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mRequestFinished) {
                        AddStock addStock = AddStock.build().setStockNum(stockNum);
                        StockCenter.doReq(addStock);
                        ((SelectStockActivity)mContext).startPopLoadingByPacMan((View) holder.itemView.getParent(), "正在添加自选股...");
                        mRequestFinished = false;
                    } else {
                        Toast.makeText(mContext, "操作太快啦~", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mStocks.size()+1;
    }

    public void setRequestFinished(boolean status){
        this.mRequestFinished = status;
    }

    class StocksHolder extends RecyclerView.ViewHolder{
        public TextView stockNumTv;
        public TextView stockNameTv;
        public Button stockCollectionBtn;
        public RippleView select_stock_item_Rv;

        public StocksHolder(View view) {
            super(view);
            this.stockNumTv = (TextView) view.findViewById(R.id.stockNumTv);
            this.stockNameTv = (TextView) view.findViewById(R.id.stockNameTv);
            this.stockCollectionBtn = (Button) view.findViewById(R.id.stockCollectionBtn);
            this.select_stock_item_Rv = (RippleView) view.findViewById(R.id.select_stock_item_Rv);
        }
    }

    class TitleHolder extends RecyclerView.ViewHolder{

        public TitleHolder(View itemView) {
            super(itemView);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new StockCursorLoader(mContext);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mStocks.clear();
        while (data.moveToNext()) {
            SimpleStock simpleStock = new SimpleStock();
            simpleStock.setStNum(data.getString(1));
            simpleStock.setStName(data.getString(2));
            simpleStock.setFirstLetter(data.getString(3));
            mStocks.add(simpleStock);
        }
        data.close();
        notifyDataSetChanged();
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    private void setEditTvFocused(){
        mSearchEt.setFocusable(true);
        mSearchEt.setFocusableInTouchMode(true);
        mSearchEt.requestFocus();
    }
}
